package com.cloudm.technician.ui.modules.common.login

import com.cloudm.technician.data.db.DbHelper
import com.cloudm.technician.data.network.CommonApi
import com.cloudm.technician.data.preferences.PreferencesHelper
import com.cloudm.technician.extensions.isMobile
import com.cloudm.technician.ui.base.RxPresenter

/**
 * 作者: wesley
 * 时间: 2017/12/14
 * 描述: 登录界面的业务逻辑
 */
class LoginPresenter(private val view: LoginContract.View, private val commonApi: CommonApi,
                     private val preferencesHelper: PreferencesHelper,
                     private val dbHelper: DbHelper) : RxPresenter(), LoginContract.Presenter {

    override fun updateBtnStatus() {
        val phoneNumber = view.getPhoneNumber()
        val password = view.getPassword()
        if (phoneNumber.isNullOrBlank() || password.isNullOrEmpty()) {
            view.btnLoginNotEnabled()
            return
        }
        view.btnLoginEnabled()
    }


    override fun updateIvClearPhoneStatus(flag: Int, s: CharSequence?) {

        when (flag) {
            0 -> {
                when (s.isNullOrBlank()) {
                    true -> view.setIvClearPhoneNotVisible()
                    false -> view.setIvClearPhoneVisible()
                }
            }

            else -> {

            }
        }
    }

    override fun updateIvClearPhoneStatus(hasFocus: Boolean) {
        when (hasFocus) {
            true -> {
                val phoneNumber = view.getPhoneNumber()
                if (phoneNumber != null && phoneNumber.isNotBlank()) {
                    view.setIvClearPhoneVisible()
                }
            }
            false -> view.setIvClearPhoneNotVisible()
        }
    }


    override fun login(mobile: String?, password: String?) {

        if (mobile == null || mobile.isNullOrBlank()) {
            view.showInputPhoneNumberMsg()
            return
        }
        if (!mobile.isMobile()) {
            view.showPhoneNumberFormatMsg()
            return
        }

        if (password == null || password.isNullOrEmpty()) {
            view.showPasswordEmptyMsg()
            return
        }

        view.showLoginDialog()
        request(commonApi.login(mobile, password), view, onSuccess = { user, _ ->
            view.hideLoginDialog()
            when (user) {
                null -> {
                    view.showUserEmptyMsg()
                }
                else -> {
                    view.loginSuccess()
                    preferencesHelper.isLogin = true
                    preferencesHelper.token = user.token
                    preferencesHelper.userId = user.id
                    dbHelper.insertOrUpdateUser(user)
                }
            }
        }, onFailure = { errorMsg ->
            view.hideLoginDialog()
            view.loginFailure(errorMsg)
        })
    }
}